{extend name="backend/public/base"}
{block name="layout"}
<div id="publicLayoutRoot">
  <div id="leftNav"></div>
  <div class="appWrapper">
    <div id="topHeader"></div>
    <div id="publicBody">
      <div id="root"></div>
    </div>
  </div>
</div>
<script>
  const e = React.createElement;
  ReactDOM.render(e(LeftNav, {
    defaultSelectedKey: location.pathname,
    logoSrc: '',
    logoStyle: {width: '0'},
    title: '元心理管理系统',
    onMenuItemClick: function (path) {
      history.pushState(null, null, path)
    },
    menus: JSON.parse('{$menu|raw}'),
  }), document.querySelector('#leftNav'));

  ReactDOM.render(e(TopHeader, {
    avatar: '{$avatar|default=""}',
    loginOutUrl: "/b/site/logout",
    nickname: '{$name|default=""}',
    description: "{$company['name']|default=''}",
    companies: JSON.parse('{$companies|raw|default="[]"}'),
    selectCompany: "{$company['id']|default=''}",
    onCompanyChange:id => {
      location.href = '/b/admin/changeCompany?company_id='+id
    }
  }), document.querySelector('#topHeader'));

  window.editorOptions = {
    file_picker_types: 'media',
    file_picker_callback: function (callback, value, meta) {
      var filetype = '.mp4';
      var upurl = "/b/site/upload?type=video";
      var input = document.createElement('input');
      input.setAttribute('type', 'file');
      input.setAttribute('accept', filetype);
      input.click();
      input.onchange = function () {
        var file = this.files[0];
        if (!file) {
          return;
        }
        var xhr, formData;
        xhr = new XMLHttpRequest();
        xhr.withCredentials = false;
        xhr.open('POST', upurl);
        xhr.onload = function () {
          var json;
          if (xhr.status === 200) {
            json = JSON.parse(xhr.responseText);
            callback(json.data.value, {title: file.name});
          }
        };
        formData = new FormData();
        formData.append('file', file, file.name);
        xhr.send(formData);
      };
    },
  };

  (function () {
    const amis = amisRequire('amis/embed');
    const appJSON = {
      type: "page",
      title: "",
      body: []
    };
    let amisScoped = amis.embed('#root', appJSON, {}, {
      // theme: 'antd',
      responseAdaptor: customResponseAdaptor,
      // 跳转新窗口存在问题
      jumpTo: function (url) {
        history.pushState(null, '', url);
      },
      /*confirm: function (title) {
        return new Promise(resolve => {
          $tools.Modal.confirm({
            title: title,
            okText: "确认",
            cancelText: "取消",
            onOk: () => resolve(true),
            onCancel: () => resolve(false)
          })
        })
      },*/
    });
    window.onpopstate = function (event) {
      loadPage(document.location)
    };

    window.addEventListener('replaceState', function (e) {
      loadPage(location.href)
    });

    window.addEventListener('pushState', function (e) {
      loadPage(location.href)
    });

    function loadPage(url) {
      // loadPageSchema(url).then(function (data) {
      new Promise((resolve, reject) => {
        axios({
          method: 'post',
          url: url,
          headers: {'X-Requested-With': 'XMLHttpRequest'},
        }).then(res => {
          const {data} = res;
          if ('string' === typeof(data)) {
            const fn = new Function(`return ${data}`);
            resolve(fn())
          } else {
            resolve(data)
          }
        }).catch(err => {
          reject(err)
        })
      }).then(function (data) {
        // 瞎补-!-
        if (data.code !== undefined && data.code === 401) {
          location.reload();
        }
        data.key = url;
        amisScoped.unmount();
        amisScoped = amis.embed('#root', data, {}, {responseAdaptor: customResponseAdaptor,});
      }).catch((err) => {
        amisScoped.unmount();
        amisScoped = amis.embed('#root', {
          "type": "page",
          "title": "Error",
          "key": "error" + new Date(),
          "body": JSON.stringify(err)
        });
      });
    }

    loadPage(location.pathname);
  })();
</script>
{/block}
